//
//  BasePageViewController.m
//  OSChina
//
//  Created by 8b410-2 on 16/12/25.
//  Copyright © 2016年 abb. All rights reserved.
//

#import "BasePageViewController.h"

@interface BasePageViewController () <UIScrollViewDelegate>

@end

@implementation BasePageViewController
- (instancetype)initWithControllers:(NSArray *)controllers Titles:(NSArray *)titles AndControllerTitle:(NSString *)title {
    self = [super init];
    if (self) {
        _controllers = controllers;
        _titles = titles;
        self.title = title;
        for (UIViewController *childVC in controllers) {
            [self addChildViewController:childVC];
        }
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setSelf];
    [self addContentView];
}

- (void)setSelf {
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
}
- (void)addContentView{
    TitleBarView *titleBar = [[TitleBarView alloc] initWithFrame:CGRectMake(0, 64, kScreen_Width, 36) andTitles:_titles];
    titleBar.backgroundColor = [UIColor titleBarColor];
    titleBar.titleButtonClicked = ^(NSUInteger index){
        [_scrollView setContentOffset:CGPointMake(kScreen_Width * index, 0) animated:YES];
    };
    _titleBar = titleBar;
    [self.view addSubview:_titleBar];
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_titleBar.frame), kScreen_Width, kScreen_Height - CGRectGetMaxY(_titleBar.frame) - 49)];
    scrollView.contentSize = CGSizeMake(kScreen_Width * _controllers.count, 0);
    scrollView.pagingEnabled = YES;
    scrollView.delegate = self;
    scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView = scrollView;
    [self.view addSubview:_scrollView];
    
    for (UIViewController *childVC in _controllers) {
        NSInteger index = [_controllers indexOfObject:childVC];
        childVC.view.frame = CGRectMake(kScreen_Width * index, 0, kScreen_Width, CGRectGetHeight(_scrollView.frame));
        [_scrollView addSubview:childVC.view];
    }
}
#pragma mark --- UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x / kScreen_Width;
    [self.titleBar scrollToCenterWithIndex:index];
}
@end
